#ifndef BASE_WORKER_H_
#define BASE_WORKER_H_

#include "constructormagic.h"
#include "messagehandler.h"

namespace base
{
	class Thread;

	// A worker is an object that performs some specific long-lived task in an
	// event-driven manner.
	class Worker : private MessageHandler
	{
	public:
		Worker();

		// Destroys this worker, but it must have already been stopped via StopWork().
		virtual ~Worker();

		// Attaches the worker to the current thread and begins processing work if not
		// already doing so.
		bool StartWork();
		// Stops processing work if currently doing so and detaches from the current
		// thread.
		bool StopWork();

	protected:
		// Signal that work is available to be done. May only be called within the
		// lifetime of a OnStart()/OnStop() pair.
		void HaveWork();

		// These must be implemented by a subclass.
		// Called on the worker thread to start working.
		virtual void OnStart() = 0;
		// Called on the worker thread when work as been signalled via HaveWork();
		virtual void OnHaveWork() = 0;
		// Called on the worker thread to stop working. Upon return, any pending
		// OnHaveWork() calls are cancelled.
		virtual void OnStop() = 0;

	private:
		// Inherited from MessageHandler
		virtual void OnMessage(Message* msg);

		// The thread that is currently doing the work.
		Thread* work_thread_;

		DISALLOW_COPY_AND_ASSIGN(Worker);
	};
}

#endif	// BASE_WORKER_H_